<?php
/**
 * Created by PhpStorm.
 * User: HP_USER
 * Date: 2018/11/8
 * Time: 11:34
 */
namespace app\admin\controller;

use app\AdminData\PlatformSetData;
use app\AdminData\ProxyManageData;
use app\common\Common;
use app\data\AdminData;
use app\data\UserData;
use messenger\Messenger;


class PlatformSet extends Base
{

    private $sortType = ['asc', 'desc'];

    private $userSort = ['create_time'];

    public function _initialize($str = null)
    {
        parent::_initialize($str); // TODO: Change the autogenerated stub
    }

//    /**
//     * 显示轮播图
//     * @return \think\response\Json
//     */
//    public function showCarouselImg()
//    {
//        $data = new PlatformSetData();
//        return json([
//            'code' => $this->t_code,
//            'msg' => 'OK',
//            'data' => $data->showCarouselImg()
//        ]);
//    }

//    /**
//     * 添加轮播图
//     * @param $data
//     * @return \think\response\Json
//     */
//    public function addCarouselImg($data)
//    {
//        if (!is_array($data) || count($data) > 4) {
//            return json(['code' => $this->f_code, 'msg' => '参数错误']);
//        }
//        $list = [];
//        $time = time();
//        foreach ($data as $k => $v) {
//            if (empty($v['picture']) || empty($v['link'])) return json(['code' => $this->f_code, 'msg' => '非法操作']);
//            $list[$k]['img'] = $v['picture'];
//            $list[$k]['url'] = $v['link'];
//            $list[$k]['create_time'] = $time;
//        }
//        $data = new PlatformSetData();
//        Db::startTrans();
//        try {
//            $data->delCarouselImg();
//            $res = $data->addCarouselImg($list);
//            if ($res) {
//                Db::commit();
//                return json(['code' => $this->t_code, 'msg' => '修改成功!']);
//            } else {
//                Db::rollback();
//                return json(['code' => $this->f_code, 'msg' => '系统繁忙请稍后在试']);
//            }
//        } catch (\Exception $e) {
//            Db::rollback();
//            return json(['code' => $this->f_code, 'msg' => $e->getMessage()]);
//        }
//    }


    private function checkCarouseImg($title, $content, $text, $status)
    {
        $t_len = mb_strlen($title);
        if ($t_len < 1 || $t_len > 20) {
            return ['code' => $this->f_code, 'msg' => '标题字数限制为1-20'];
        }
        $c_len = mb_strlen($content);
        if ($c_len < 10 || $c_len > 5000) {
            return ['code' => $this->f_code, 'msg' => '内容字数超标'];
        }
        $text_len = mb_strlen($text);
        if ($text_len < 1 || $text_len > 5000) {
            return ['code' => $this->f_code, 'msg' => '内容字数超标'];
        }
        if (!in_array($status, [0, 2])) {
            return ['code' => $this->f_code, 'msg' => '内容字数超标'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 资讯添加
     * @param $title
     * @param $img
     * @param $content
     * @param $text
     * @param $status
     * @return \think\response\Json
     */
    public function addCarouselImg($title, $img, $content, $text, $status)
    {
        $time = time();
        $res = $this->checkCarouseImg($title, $content, $text, $status);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (Common::checkTableFields('drh_carousel_img', 'title', $title) == $this->t_code) {
            return json(['code' => $this->f_code, 'msg' => '标题重复']);
        }
        $data = new PlatformSetData();
        $res = $data->addCarouselImg($title, $img, $content, $time, $text, $status);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '保存成功!']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '系统繁忙请稍后在试']);
        }
    }

    /**
     * 显示轮播图
     * @param $page
     * @param $pre
     * @param $value
     * @param array $sort
     * @return \think\response\Json
     */
    public function showCarouselImg($page = 1, $pre = 15, $sort = ['create_time' => 'desc'], $value = 0)
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->userSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $where = '';
        if ($value !== 0) {
            if (is_numeric($value) && $value > 0) {//搜索的id
                $where = " id={$value}";
            } else {
                $where = "title like '%{$value}%'";
            }
        }
        $data = new PlatformSetData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $data->showCarouselImg($page, $pre, $sort, $where),
                'total' => Common::total($where, 'drh_carousel_img')
            ]
        ]);
    }

    /**
     * 是否发布
     * @param $ids
     * @param $status
     * @return \think\response\Json
     */
    public function releaseCarouselImg($ids, $status)
    {
        if (!is_array($ids)) {
            return json(['code' => $this->f_code, 'msg' => '参数类型错误']);
        }
        if (count($ids) > 20) {
            return json(['code' => $this->f_code, 'msg' => '批量修改数量超标']);
        }
        if (!in_array($status, [0, 1])) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $ids = implode(',', $ids);
        $where = " id in ($ids)";
        $data = new PlatformSetData();
        $time = time();
        $res = $data->releaseCarouselImg($where, $status, $time);
        if ($res)
            return json(['code' => $this->t_code, 'msg' => '修改成功']);
        else
            return json(['code' => $this->f_code, 'msg' => '修改失败请稍后再试']);
    }

    /**
     * 显示轮播图内容
     * @param $id
     * @return \think\response\Json
     */
    public function showCarouselImgInfo($id)
    {
        if (Common::checkTableFields('drh_carousel_img', 'id', $id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在']);
        };
        $data = new PlatformSetData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data->showCarouselImgInfo($id)
        ]);
    }

    /**
     * 修改轮播图内容
     * @param $id
     * @param $title
     * @param $content
     * @param $img
     * @param $text
     * @param $status
     * @return \think\response\Json
     */
    public function changeCarouselImgInfo($id, $title, $content, $img, $text, $status)
    {
        if (Common::checkTableFields('drh_carousel_img', 'id', $id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在']);
        };
        $res = $this->checkCarouseImg($title, $content, $text, $status);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $res = Common::getTableValue('drh_carousel_img', 'id', 'title', $title);
        if (!empty($res) && $res != $id) {
            return json(['code' => $this->f_code, 'msg' => '标题重复']);
        }
        $time = time();
        $data = new PlatformSetData();
        $res = $data->changeCarouselImgInfo($id, $title, $content, $img, $time, $text, $status);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '修改成功']);
        } else {
            return json(['code' => $this->t_code, 'msg' => '修改失败请稍后在试']);
        }
    }

    /**
     * 显示轮播图标题图片
     * @return \think\response\Json
     */
    public function showCarouselImgTitle()
    {
        $data = new PlatformSetData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data->showCarouselImgTitle()
        ]);
    }

    /**
     * 删除轮播图
     * @param $ids
     * @return \think\response\Json
     */
    public function delCarouselImg($ids)
    {
        if (!is_array($ids)) {
            return json(['code' => $this->f_code, 'msg' => '参数类型错误']);
        }
        $ids = implode(',', $ids);
        $where = " id in ($ids)";
        $data = new PlatformSetData();
        $res = $data->delCarouselImg($where);
        if ($res) {
            return json(['code' => $this->t_code, 'msg' => '删除成功']);
        } else {
            return json(['code' => $this->f_code, 'msg' => '删除失败请稍后在试']);
        }
    }


    /**
     * 消息设置
     * @param int $user_id
     * @param int $type
     * @param int $tel
     * @param int $send_type
     * @param string $msg
     * @param string $additional_mgs
     * @return \think\response\Json
     */
    public function msgConfig($user_id = 0, $type = -1, $tel = 0, $send_type = 1, $msg = '', $additional_mgs = '')
    {
        if ($send_type == 2) {//短信
            return $this->sendTelMsg(new Messenger(), $tel, $msg);
        } else if ($send_type == 3 || $send_type == 4 || $send_type == 5) {//普通
            return json($this->sendAllUserMsg($send_type, $msg, time(), new PlatformSetData()));
        } else {//消息
            $data = new PlatformSetData();
            $time = time();
            if ($user_id != 0) {
                return json($this->sendUserMsg($user_id, $msg, $time, $data, $additional_mgs));
            } else if ($tel != 0) {
                return json($this->sendUserTelMsg($tel, $msg, $time, $data, $additional_mgs));
            } else {//批量
                return json($this->sendUsersMsg($type, $msg, $time, $data));
            }
        }
    }

    private function sendAllUserMsg($type, $msg, $time, PlatformSetData $data)
    {
        if ($type == 4) {
            $where = ' verify_status = 1 and recover_status = 0 ';
            $total = Common::total($where, 'drh_original_member');//获取总人数
            $num = ceil($total / 500);//循环次数
            $table_name = 'drh_original_member';
            $value = 'user_id';
        } else if ($type == 5) {
            $where = 'verify_status = 1 and recover_status = 0 ';
            $total = Common::total($where, 'drh_shop');//获取总人数
            $num = ceil($total / 500);//循环次数
            $table_name = 'drh_shop';
            $value = 'user_id';
        } else {
            $where = ' user_lv=1 and recover_status=0 ';
            $total = Common::total($where, 'drh_user_info');//获取总人数
            $num = ceil($total / 500);//循环次数
            $table_name = 'drh_user_info';
            $value = 'id';
        }
        try {
            for ($i = 0; $i < $num; $i++) {
                $info = $data->getUserId($where, $i + 1, $table_name, $value);
                $list = [];
                foreach ($info as $k => $v) {
                    $list[$k]['user_id'] = $v[$value];
                    $list[$k]['msg'] = $msg;
                    $list[$k]['create_time'] = $time;
                    $list[$k]['type'] = 2;
                }
                $data->batchSendMsg($list);
            }
            return ['code' => $this->t_code, 'msg' => '发送成功'];
        } catch (\Exception $e) {
            Common::debug("短信发送错误:", json_encode(['time' => $time, 'num' => $num,
                'type' => $type, 'msg' => $msg]), 'msg.txt');
            return ['code' => $this->f_code, 'msg' => $e->getMessage()];
        }

    }


    /**
     * 用户发送消息（站内）
     * @param $user_id
     * @param $msg
     * @param $time
     * @param PlatformSetData $data
     * @param $additional_mgs
     * @return array
     */
    public function sendUserMsg($user_id, $msg, $time, PlatformSetData $data, $additional_mgs)
    {
        $res = $data->sendUserMsg($user_id, $msg, $time, $additional_mgs);
        if ($res) {
            return ['code' => $this->t_code, 'msg' => '发送成功!'];
        } else {
            return ['code' => $this->f_code, 'msg' => '发送失败!请稍后在试'];
        }
    }

    /**
     * 根据手机号发送信息（站内）
     * @param $tel
     * @param $msg
     * @param $time
     * @param PlatformSetData $data
     * @return array
     */
    public function sendUserTelMsg($tel, $msg, $time, PlatformSetData $data, $additional_mgs)
    {
        $user_id = Common::getTableValue('drh_user_info', 'id', 'user_tel', $tel);
        if (empty($user_id)) return ['code' => $this->f_code, 'msg' => '不存在该用户'];
        $res = $data->sendUserMsg($user_id, $msg, $time, $additional_mgs);
        if ($res) {
            return ['code' => $this->t_code, 'msg' => '发送成功!'];
        } else {
            return ['code' => $this->f_code, 'msg' => '发送失败!请稍后在试'];
        }
    }

    /**
     * 发送短信消息
     * @param Messenger $msg
     * @param $tel
     * @param $info
     * @return \think\response\Json
     */
    public function sendTelMsg(Messenger $msg, $tel, $info)
    {
        $con = $msg->msgSend($tel, $info);
        if ($con['code'] == '0') {//发送成功
            return json(['code' => $this->t_code, 'msg' => '发送成功!']);
        } else {//发送失败
            return json(['code' => $this->f_code, 'msg' => '发送失败请稍后在试!']);
        }
    }

    /**
     * 批量发送信息
     * @param $type
     * @param $msg
     * @param $time
     * @param PlatformSetData $data
     * @return array|\think\response\Json
     */
    public function sendUsersMsg($type, $msg, $time, PlatformSetData $data)
    {
        if (!in_array($type, [-1, 1, 2, 3, 4, 5, 6])) {
            return ['code' => $this->f_code, 'msg' => '状态错误'];
        }
        $where = '';
        if ($type == -1) {
            $total = Common::total('', 'drh_user_info');//获取总人数
            $num = ceil($total / 500);//循环次数
        } else if ($type == 6) {
            $total = Common::total('recover_status=1', 'drh_user_info');//获取总人数
            $num = ceil($total / 500);//循环次数
        } else {
            $total = Common::total("user_lv={$type} and recover_status=0", 'drh_user_info');//获取总人数
            $num = ceil($total / 500);//循环次数
        }
        try {
            for ($i = 0; $i < $num; $i++) {
                $info = $data->getUserId($where, $i + 1);
                $list = [];
                foreach ($info as $k => $v) {
                    $list[$k]['user_id'] = $v['id'];
                    $list[$k]['msg'] = $msg;
                    $list[$k]['create_time'] = $time;
                    $list[$k]['type'] = 2;
                }
                $data->batchSendMsg($list);
            }
            return ['code' => $this->t_code, 'msg' => '发送成功'];
        } catch (\Exception $e) {
            Common::debug("短信发送错误:", json_encode(['time' => $time, 'num' => $num,
                'type' => $type, 'msg' => $msg]), 'msg.txt');
            return ['code' => $this->f_code, 'msg' => $e->getMessage()];
        }
    }

    private function chenckDistributionFlow($p_id, $user_id, $money, $type)
    {
        if (!in_array($type, [1, 2])) {
            return ['code' => $this->f_code, 'msg' => "推荐类型错误"];
        }
        $res = Common::getTableValue('drh_user_friend', 'id', ['user_id', 'friend_id'], [$p_id, $user_id]);
        if (empty($res)) {
            return ['code' => $this->f_code, 'msg' => "错误的上下级关系"];
        }
        $res = Common::getTableValue('drh_user_info', 'id', ['id', 'recover_status'], [$p_id, 0]);
        if (empty($res)) {
            return ['code' => $this->f_code, 'msg' => "用户已被禁用不支持分佣"];
        }
        $res = Common::getTableValue('drh_user_info', 'id', ['id', 'recover_status'], [$user_id, 0]);
        if (empty($res)) {
            return ['code' => $this->f_code, 'msg' => "用户已被禁用不支持分佣"];
        }
        if (is_numeric($money) || $money < 0) {
            return ['code' => $this->f_code, 'msg' => "s输入金额错误"];
        }
        return ['code' => $this->t_code, 'msg' => 'OK'];
    }

    /**
     * @param $p_id
     * @param $user_id
     * @param $money
     * @param $type
     * @return \think\response\Json
     * @throws \Exception
     */
    public function addDistributionFlow($p_id, $user_id, $money, $type)
    {
        $res = $this->chenckDistributionFlow($p_id, $user_id, $money, $type);
        if ($res['code'] == $this->f_code) return json($res);
        switch ($type) {
            case 1:
                $msg = "推荐商户分销,用户id:{$user_id}";
                $other_money = 7800;
                $type = 11;
                break;
            case 2:
                $msg = "推荐区域代理分销,用户id:{$user_id}";
                $other_money = $money * 0.1;
                $type = 12;
                break;
            default:
                throw new \Exception('系统错误请稍后在试 error:400');
        }
        $fees = $money - $other_money;
        $order_num = $type . '-' . $user_id;
        $res = Common::getTableValue('drh_user_flow', 'id', ['msg', 'user_id', 'order_num'], [$msg, $p_id, $order_num]);
        if (!empty($res)) {
            return json(['code' => $this->f_code, 'msg' => "请勿重复提交"]);
        }
        $user = new UserData();
        $user_info = $user->getInfo($user_id, ['user_integral', 'user_money', 'user_name'], 'id');
        $time = time();
        $user->addUserFlow($user_id, $user_info['user_integral'], $user_info['user_money'],
            $time, $other_money, 0, $order_num, 4, $user_info['user_money'] + $other_money,
            $user_info['user_integral']);
        $user->endOrder($p_id, $user_info['user_money'] + $other_money, $user_info['user_integral']);
        $admin = new AdminData();
        $admin->addPlatformFlow($fees, $time, $order_num, 1);//加入平台收入
        return json(['code' => $this->t_code, 'msg' => '添加成功']);
    }

}